package org.xiaojinlong.exam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jin Long
 *         2015/10/17
 */
public class T151017 {
    public static int[] intersection(int[] a, int[] b) {
        Arrays.sort(a);
        Arrays.sort(b);
        int i = 0, j = 0;
        List<Integer> result = new ArrayList<>();
        while (i < a.length || j < b.length) {
            if (i >= a.length || a[i] > b[j]) {
                result.add(b[j++]);
                while (j < b.length && b[j] == b[j-1]) j++;
            } else if (j >= b.length || a[i] < b[j]) {
                result.add(a[i++]);
                while (i < a.length && a[i] == a[i-1]) i++;
            } else {
                result.add(a[i++]);
                while (i < a.length && a[i] == a[i-1]) i++;
                j++;
                while (j < b.length && b[j] == b[j-1]) j++;
            }
        }
        int[] res = new int[result.size()];
        for (int k = 0; k < res.length; k++)
            res[k] = result.get(k);
        return res;
    }

    public static void main(String[] args) {
        int[] a = { 1, 1, 2, 3, 3, 4 };
        int[] b = { 2, 2, 5, 6, 8 };
        System.out.println(Arrays.toString(intersection(a, b)));
    }
}
